package io.renren.modules.cp.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.exception.RRException;
import io.renren.modules.app.dao.BimUserDao;
import io.renren.modules.cp.config.WxCpConfiguration;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import io.renren.modules.app.utils.JwtUtils;


import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @author: zlm
 * @date: 2020年07月21日 5:03 下午
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/cp/login/{agentId}")
public class WxLoginController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BimUserDao bimUserDao;

    @Autowired
    private JwtUtils jwtUtils;


    @GetMapping("/userinfo")
    public Object login(@PathVariable Integer agentId, @RequestParam(name = "code")  String code)  {

        if (StringUtils.isAnyBlank(code)){
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        try{
            WxCpOauth2UserInfo res =  wxCpService.getOauth2Service().getUserInfo(code);
            String userName = res.getUserId();
            Map<String,String> userPks=  bimUserDao.queryUserPks(userName);
            String jsonStr = null;
            try {
                jsonStr = new ObjectMapper().writeValueAsString(userPks);
            } catch (JsonProcessingException e) {
                logger.error(e.toString());
                throw new RRException("未授权，拒绝访问",  HttpStatus.FORBIDDEN.value());
            }
            logger.debug(jsonStr);
            if("null".equals(jsonStr)){
                throw new RRException("未授权，拒绝访问",  HttpStatus.NOT_FOUND.value());
            }
            //生成token
            String token = jwtUtils.generateToken(jsonStr);

            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());

            return map;
        }catch (WxErrorException err){
            logger.error(err.toString());
            throw new RRException(err.toString(), HttpStatus.UNAUTHORIZED.value());
        }

    }
    @GetMapping("/authorizationurl")
    public String redirect(@PathVariable Integer agentId, @RequestParam(name = "url")  String url) throws WxErrorException {

        if (StringUtils.isAnyBlank(url)){
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        String res =  wxCpService.getOauth2Service().buildAuthorizationUrl(url,"STATE");;
        return res;
    }
}
